from flask import jsonify, render_template, current_app, flash, redirect, url_for
from flask_login import login_required, current_user
from . import web
from app.models.gift import Gift
from app.models.drift import Drift
from app.models.base import db
from app.view_models.trade import MyTrades
from app.libs.enums import PendingStatus


@web.route('/my/gifts')
@login_required  # 登录验证装饰器
def my_gifts():
    # 我上传的书籍数据
    gifts_of_mine = Gift.get_user_gifts(current_user.id)
    isbn_list = [gift.isbn for gift in gifts_of_mine]
    # 书籍心愿数量统计
    wish_count_list = Gift.get_wish_count(isbn_list)
    # 数据合并与修饰
    view_model = MyTrades(gifts_of_mine, wish_count_list)

    return render_template('my_gifts.html', gifts=view_model.trades)


@web.route('/gifts/book/<isbn>')
@login_required
def save_to_gifts(isbn):
    """
    赠送书籍
    :param isbn:
    :return:
    """
    if current_user.can_save_to_list(isbn):
        with db.auto_commit():
            gift = Gift()
            gift.isbn = isbn
            gift.uid = current_user.id
            # 赠送用户获取平台奖励鱼豆
            current_user.beans += current_app.config['BEANS_UPLOAD_ONE_BOOK']
            db.session.add(gift)
            flash('赠送成功', category='success')
    else:
        flash('这本书已经添加到你的赠送清单或心愿清单，请不要重复添加')
    return redirect(url_for('web.book_detail', isbn=isbn))


@web.route('/gifts/<gid>/redraw')
@login_required
def redraw_from_gifts(gid):
    """
    撤销礼物
    :param gid:
    :return:
    """
    gift = Gift.query.filter_by(id=gid, launched=False).first_or_404()
    # 当前书籍是否存在未完成的交易
    if Drift.query.filter_by(gift_id=gid, pending=PendingStatus.Waiting).count():
        flash('这个礼物正处于交易状态，请先前往鱼漂完成该交易')
    else:
        with db.auto_commit():
            gift.delete()
            # 撤销平台奖励
            current_user.beans -= current_app.config['BEANS_UPLOAD_ONE_BOOK']
    return redirect(url_for('web.my_gifts'))
